<template>
  <!-- 获取批量入库异常与否弹框 -->
  <el-dialog :visible.sync="abnormalOrderFlag" center :append-to-body="true" :lock-scroll="false" width="90%" z-index="2007">
    <div style="width: 100%;">
      <div class="tablist">
        <span class="name" v-for="(item,index) in tabs" :class="{active:(indexs==index)}" @click="handleTabs(index)"
          :key="index">{{item.name}}</span>
      </div>
      <div v-if="indexs==0">
        <el-table :data="getNotReadOrderNewsLogList" style="width: 100%" border>
          <el-table-column prop="goodsName" align="center" width="180" label="蛋糕名称" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="goodsSpecs" align="center" width="180" label="规格" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="regionName" align="center" width="90" label="地区" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="warehouseName" align="center" width="90" label="仓库" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="xmbzNo" align="center" width="180" label="后台单号" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="remarks" align="center" width="90" label="备注" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="printingState" label="打印状态" align="center" width="100">
            <template slot-scope="{row}">
              <span v-if='row.printingState==1'>未打印</span>
              <span v-if='row.printingState==2'>已打印</span>
            </template>
          </el-table-column>
          <el-table-column prop="newsTypeName" align="center" width="90" label="目前进度">
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <span v-show="scope.row.productionProcess == 6">
                <el-button v-show="scope.row.newsType != 3" plain size="mini" @click="productionSelect(scope.$index, scope.row, 1)">继续生产</el-button>
                <el-button plain size="mini" @click="productionSelect(scope.$index, scope.row, 2)">报损蛋糕</el-button>
                <el-button plain size="mini" @click="productionSelect(scope.$index, scope.row, 3)">不生产</el-button>
              </span>
              <el-button class="ml-10" plain size="mini" @click="showLog(scope.row)">查看日志</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="getNotReadOrderNewsLogQuery.page" :limit.sync="getNotReadOrderNewsLogQuery.size"
          @pagination="getAbnormalList" />
      </div>
      <div v-if='indexs==1'>
        <el-form :inline="true" :model="AbnormalrecordListQuery" class="demo-form-inline Abnormalrecord-inline">
          <el-form-item>
            <el-date-picker v-model="Time" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" size='small'
              :default-time="['00:00:00', '23:59:59']">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="类别">
            <el-select
              v-model="AbnormalrecordListQuery.category"
              placeholder="类别"
              size="small"
              class="w-100"
            >
              <el-option
                v-for="(item, index) in orderCategoryList"
                :key="index"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-button class="mt-4" type="primary" plain size="small" icon="el-icon-search" @click="handleFilter(Time)">查询</el-button>
        </el-form>
        <el-table :data="getAbnormalrecordList" style="width: 100%" border>
          <el-table-column prop="goodsName" align="center" width="180" label="蛋糕名称" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="goodsSpecs" align="center" width="180" label="规格" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="regionName" align="center" width="90" label="地区" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="warehouseName" align="center" width="90" label="仓库" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="xmbzNo" align="center" width="180" label="后台单号" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="remarks" align="center" width="90" label="备注" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="printingState" label="打印状态" align="center" width="100">
            <template slot-scope="{row}">
              <span v-if='row.printingState==1'>未打印</span>
              <span v-if='row.printingState==2'>已打印</span>
            </template>
          </el-table-column>
          <el-table-column prop="productionProcessName" align="center" label="操作记录">
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button plain size="mini" @click="showLog(scope.row)">查看日志</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="Abnormalrecordtotal>0" :total="Abnormalrecordtotal" :page.sync="AbnormalrecordListQuery.page"
                  :limit.sync="AbnormalrecordListQuery.size" @pagination="getAbnormalrecordLists" />
      </div>
    </div>
    <!-- </div> -->

    <orderLogDialog ref="orderLogDialog"></orderLogDialog>
  </el-dialog>
</template>

<script>
import {
  getNotReadOrderNewsLog, // 退订改期异常记录
  confirmProductionToWarehousingLog,// 确认继续生产并入库记录
  refundChoice, // 退款
  productionChoice, // 退订
} from "@/api/shop";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import orderLogDialog from '@/components/dialog/orderLogDialog'
const orderCategoryList = [
  {
    label: '蛋糕',
    value: '0',
  },
  {
    label: '下午茶',
    value: '1',
  }
]

export default {
  props: {
    mainWarehouseId: {
    },
    warehouseId: {
    },
  },
  data() {
    return {
      indexs: 0,
      orderCategoryList,
      Time: [
        this.dayjs(new Date())
          .format("YYYY-MM-DD 00:00:00")
          .toString(),
        this.dayjs(new Date())
          .format("YYYY-MM-DD 00:00:00")
          .toString()
      ],
      abnormalOrderFlag: false,
      tabs: [
        //标签数据
        {
          name: "异常订单列表"
        },
        {
          name: "异常订单记录"
        },
      ],
      getNotReadOrderNewsLogList: [],
      getAbnormalrecordList: [],
      Abnormalrecordtotal: 0,
      AbnormalrecordListQuery: {
        cityId: JSON.parse(window.localStorage.getItem("saber-areaId")).content,
        limit: 10,
        page: 1,
        size: 10,
        productionProcess: "0",
        category: '0',
        newsType: '2,3',
        startTime: this.dayjs(new Date()).format("YYYY-MM-DD"),
        endTime: this.dayjs(new Date()).format("YYYY-MM-DD"),
      },
      productionChoiceQuery: { // 生产部生产流程选择请求列表
        id: '',
        productionProcess: '',
        orderId: '',
        orderDetailId: '',
        // remarks: '',
        promoter: ''
      },
      total: 0,
      getNotReadOrderNewsLogQuery: {
        cityId: JSON.parse(window.localStorage.getItem("saber-areaId")).content,
        limit: 10,
        page: 1,
        size: 10,
        mainWarehouseId: '', // 总仓id
        warehouseId: '', // 分仓id
        productionProcess: '6',
        newsType: '2,3',
        startTime: this.dayjs(
            new Date(new Date().getTime()-72*60*60*1000)
          )
          .format("YYYY-MM-DD"),
        endTime: this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD"),
      },
    };
  },
  methods: {
    show() {
      this.abnormalOrderFlag = true
      this.getAbnormalList()
    },
    setTimer() {
      if(this.farmingTimer !== null) {
        window.clearInterval(this.farmingTimer)
      }
      this.farmingTimer = setInterval(() => {
        this.getAbnormalList().then(res => {
          if (res && res.length > 0) {
            this.playTip()
          }
        })
      }, 30 * 1000)
    },
    clearTimer() {
      this.farmingTimer && clearInterval(this.farmingTimer)
      this.farmingTimer = null
    },
    getAbnormalList() {
      let disabledArray = [];
      // 异常订单记录
      return getNotReadOrderNewsLog({
        ...this.getNotReadOrderNewsLogQuery,
        mainWarehouseId: this.mainWarehouseId,
        warehouseId: this.warehouseId,
      }).then(res => {
        this.total = res.data.data.total;
        this.getNotReadOrderNewsLogList = res.data.data.rows;
        if (res.data.data.rows.length > 0) {
          this.getNotReadOrderNewsLogList.forEach(item => {
            if (item.productionProcess == 6) {
              disabledArray.push(false);
            }
          })
          if (disabledArray.indexOf(false) > -1) {
            this.abnormalOrderFlag = true;// 异常列表Flag
          }
        }
        return this.getNotReadOrderNewsLogList
      })
    },
    // 播放声音提醒
    playTip() {
      if (!this.audio) {
        this.audio = new Audio('/mideo/abnormal.mp3');
      }
      this.audio.play();
    },
    getAbnormalrecordLists() {
      getNotReadOrderNewsLog(this.AbnormalrecordListQuery).then(res => {
        this.Abnormalrecordtotal = res.data.data.total;
        this.getAbnormalrecordList = res.data.data.rows;
      });
    },
    handleTabs(item) {
      this.indexs = item;
      if (this.indexs == 0) {
        this.getAbnormalList() // 异常订单记录
      } else {
        this.Time=[
          this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD 00:00:00")
          .toString(),
          this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD 00:00:00")
          .toString(),

        ],
        this.AbnormalrecordListQuery.page = 1;
        getNotReadOrderNewsLog(this.AbnormalrecordListQuery).then(res => {
          this.Abnormalrecordtotal = res.data.data.total;
          this.getAbnormalrecordList = res.data.data.rows;
        })
      }
    },
    handleFilter(item) {
      if (item) {
        this.AbnormalrecordListQuery.startTime = this.dayjs(item[0])
          .format("YYYY-MM-DD")
          .toString();
        this.AbnormalrecordListQuery.endTime = this.dayjs(item[1])
          .format("YYYY-MM-DD")
          .toString();
      }
      var time1 = Date.parse(this.AbnormalrecordListQuery.startTime);
      var time2 = Date.parse(this.AbnormalrecordListQuery.endTime);
      //讲两个时间相减，求出相隔的天数
      var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
      if (dayCount > 31) {
        this.$message({
          showClose: true,
          message: "时间间隔不可超过31天",
          type: "warning"
        });
      } else {
        this.getAbnormalrecordLists();
      }
    },
    abnormalClick() {
      // 异常订单
      this.getAbnormalList(); // 异常订单记录
    },
    productionSelect(index, row, dictKey) {
      // console.log(row, 'e.currentTarget.dataset')
      this.productionChoiceQuery.id = row.id
      this.productionChoiceQuery.orderId = row.orderId
      this.productionChoiceQuery.orderDetailId = row.orderDetailId
      this.productionChoiceQuery.productionProcess = dictKey
      this.productionChoiceQuery.promoter = row.promoter
      let remarks = row.remarks
      if(dictKey == 1) {
        this.$confirm('操作【继续生产】，请在3小时内点击【入库】', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          showClose: false,// 右上角关闭按钮
          showCancelButton: false,// 取消按钮
          closeOnClickModal: false,// 点击遮罩关闭
          closeOnPressEscape: false,// 按下 ESC 键关闭
        }).then(() => {
          this.queryChoice(remarks);
          confirmProductionToWarehousingLog({orderId: row.orderId}).then(res => {
            console.log('res.data.data',res.data.data);
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      } else {
        this.queryChoice(remarks);
      }
    },
    queryChoice(remarks) {
      if (remarks === '退订') {
        productionChoice(this.productionChoiceQuery).then(res => {
          if (res.data.code == 200) {
            this.$notify({
              title: '操作成功',
              message: '请您耐心等待',
              type: 'success'
            })
            this.getAbnormalList() // 异常订单记录
          }
        })
      } else if (remarks === '退款') {
        refundChoice(this.productionChoiceQuery).then(res => {
          if (res.data.code == 200) {
            this.$notify({
              title: '操作成功',
              message: '请您耐心等待',
              type: 'success'
            })
            this.getAbnormalList() // 异常订单记录
          }
        })
      }
    },
    showLog(data) {
      this.$refs.orderLogDialog.show({orderId: data.orderId})
    }
  },
  mounted() {
    this.setTimer()
    this.getAbnormalList()
  },
  destroyed() {
    this.clearTimer()
  },
  components: {
    Pagination,
    orderLogDialog
  }
};
</script>
<style lang="scss" scoped>
.tablist {
  display: flex;
  margin-bottom: 20px;

  .name {
    padding: 0 20px;
    text-align: center;
    color: #000;
    font-size: 20px;
    line-height: 40px;
    cursor: pointer;

    &.active {
      font-size: 20px;
      color: #43a0ff;
      border-bottom: 1px solid #43a0ff;
    }
  }
}
</style>
